package icu.cqcai.xinsi.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import icu.cqcai.xinsi.domain.InterviewAnalysis;
import icu.cqcai.xinsi.domain.InterviewAnswer;
import icu.cqcai.xinsi.domain.InterviewSession;
import icu.cqcai.xinsi.mapper.InterviewAnalysisMapper;
import icu.cqcai.xinsi.mapper.InterviewAnswerMapper;
import icu.cqcai.xinsi.mapper.InterviewSessionMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 面试评估工作流服务
 */
@Service
public class InterviewEvaluationService {

    private static final Logger logger = LoggerFactory.getLogger(InterviewEvaluationService.class);

    // 扣子工作流配置 - 面试评估工作流
    private static final String COZE_WORKFLOW_API_URL = "https://api.coze.cn/v1/workflow/run";
    private static final String ACCESS_TOKEN = "pat_SwmNZRUPekSdjR31xF4jXMlc6tAV4k50Hiy6dZIsJLVmgK7VUk2gfsKWRTEbDO49";
    private static final String SPACE_ID = "7514500344975212563";
    private static final String WORKFLOW_ID = "7516857061499502592";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private InterviewSessionMapper interviewSessionMapper;

    @Autowired
    private InterviewAnswerMapper interviewAnswerMapper;

    @Autowired
    private InterviewAnalysisMapper interviewAnalysisMapper;

    /**
     * 评估面试会话
     */
    public Map<String, Object> evaluateInterview(Long userId, String sessionId) {
        // 首先，将状态更新为"评估中"
        interviewSessionMapper.updateEvaluationStatus(sessionId, "评估中");

        try {
            logger.info("开始评估面试会话: userId={}, sessionId={}", userId, sessionId);

            // 1. 验证会话归属
            InterviewSession session = interviewSessionMapper.findBySessionId(sessionId);
            if (session == null) {
                throw new RuntimeException("面试会话不存在");
            }
            if (!session.getUserId().equals(userId)) {
                throw new RuntimeException("无权访问此面试会话");
            }

            // 2. 获取答案列表（忽略status字段，获取所有题目）
            List<InterviewAnswer> answers = interviewAnswerMapper.selectAllAnswersByUserAndSession(userId, sessionId);
            
            if (answers.isEmpty()) {
                throw new RuntimeException("没有找到面试题目，请先生成面试题目");
            }
            
            logger.info("找到面试题目数: {}", answers.size());

            // 3. 构建工作流请求
            Map<String, Object> workflowRequest = buildEvaluationRequest(session, answers);

            // 4. 调用扣子工作流
            String response = callCozeWorkflow(workflowRequest);

            // 5. 解析评估结果
            Map<String, Object> evaluationResult = parseEvaluationResponse(response);

            // 6. 保存评估结果到数据库
            saveEvaluationResult(userId, sessionId, evaluationResult);
            
            // 评估成功后，更新状态为"评估完成"
            interviewSessionMapper.updateEvaluationStatus(sessionId, "评估完成");

            logger.info("面试评估完成: sessionId={}", sessionId);
            return evaluationResult;

        } catch (Exception e) {
            // 评估失败后，更新状态为"评估失败"
            interviewSessionMapper.updateEvaluationStatus(sessionId, "评估失败");
            logger.error("面试评估失败: sessionId={}", sessionId, e);
            throw new RuntimeException("面试评估失败: " + e.getMessage(), e);
        }
    }

    /**
     * 构建评估工作流请求
     */
    private Map<String, Object> buildEvaluationRequest(InterviewSession session, List<InterviewAnswer> answers) {
        // 构建答案数组（包含所有题目，不管是否有回答）
        List<Map<String, Object>> answersArray = new ArrayList<>();
        for (InterviewAnswer answer : answers) {
            Map<String, Object> answerMap = new HashMap<>();
            answerMap.put("questionId", answer.getQuestionId());
            answerMap.put("questionTitle", answer.getQuestionTitle());
            answerMap.put("questionContent", answer.getQuestionContent());
            answerMap.put("questionCategory", answer.getQuestionCategory());
            // 如果回答内容为空，传递空字符串给AI让其判断
            answerMap.put("answerContent", answer.getAnswerContent() != null ? answer.getAnswerContent() : "");
            answerMap.put("answerDuration", answer.getAnswerDuration() != null ? answer.getAnswerDuration() : 0);
            answersArray.add(answerMap);
        }

        // 构建输入参数
        Map<String, Object> inputParams = new HashMap<>();
        inputParams.put("sessionId", session.getSessionId());
        inputParams.put("targetPosition", session.getTargetPosition());
        inputParams.put("workExperience", session.getWorkExperience());
        inputParams.put("skills", session.getSkills());
        inputParams.put("answers", answersArray);

        // 构建工作流请求 - 根据扣子工作流API正确格式
        Map<String, Object> workflowRequest = new HashMap<>();
        workflowRequest.put("workflow_id", WORKFLOW_ID);
        workflowRequest.put("parameters", inputParams); // 直接传递参数，不使用_input嵌套

        logger.debug("评估工作流请求参数: {}", workflowRequest);
        return workflowRequest;
    }

    /**
     * 调用扣子工作流API
     */
    private String callCozeWorkflow(Map<String, Object> request) {
        try {
            logger.info("调用面试评估工作流API: {}", COZE_WORKFLOW_API_URL);

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.setBearerAuth(ACCESS_TOKEN);
            headers.set("User-Agent", "xinsi-interview-evaluation/1.0");

            // 创建请求实体
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(request, headers);

            // 发送请求
            ResponseEntity<String> response = restTemplate.postForEntity(
                COZE_WORKFLOW_API_URL, entity, String.class);

            logger.info("评估工作流响应状态码: {}", response.getStatusCode());

            String responseBody = response.getBody();
            if (response.getStatusCode() == HttpStatus.OK) {
                return responseBody;
            } else {
                logger.error("评估工作流调用失败，状态码: {}, 响应体: {}", response.getStatusCode(), responseBody);
                throw new RuntimeException("评估工作流调用失败，状态码: " + response.getStatusCode());
            }

        } catch (Exception e) {
            logger.error("调用评估工作流API异常", e);
            throw new RuntimeException("评估工作流API调用异常: " + e.getMessage(), e);
        }
    }

    /**
     * 解析评估工作流响应
     */
    private Map<String, Object> parseEvaluationResponse(String response) {
        try {
            logger.info("=== 开始解析评估响应 ===");
            logger.info("原始响应: {}", response);

            // 解析响应JSON
            JsonNode rootNode = objectMapper.readTree(response);
            logger.info("解析后的根节点: {}", rootNode);
            
            // 检查响应是否成功
            if (rootNode.has("code")) {
                int code = rootNode.get("code").asInt();
                logger.info("响应状态码: {}", code);
                if (code != 0) {
                    String message = rootNode.has("msg") ? rootNode.get("msg").asText() : "未知错误";
                    logger.error("扣子API调用失败，错误码: {}, 错误信息: {}", code, message);
                    throw new RuntimeException("扣子API调用失败: " + message);
                }
            }
            
            // 查找data字段
            JsonNode dataNode = null;
            if (rootNode.has("data")) {
                dataNode = rootNode.get("data");
                logger.info("找到data节点: {}", dataNode);
                
                // 如果data是字符串，需要再次解析
                if (dataNode.isTextual()) {
                    String dataString = dataNode.asText();
                    logger.info("data是字符串，内容: {}", dataString);
                    dataNode = objectMapper.readTree(dataString);
                    logger.info("解析data字符串后: {}", dataNode);
                }
            } else {
                logger.warn("响应中没有找到data字段");
            }

            // 查找output字段
            String outputText = null;
            if (dataNode != null && dataNode.has("output")) {
                outputText = dataNode.get("output").asText();
                logger.info("从data.output找到内容: {}", outputText);
            } else if (rootNode.has("output")) {
                outputText = rootNode.get("output").asText();
                logger.info("从根级output找到内容: {}", outputText);
            } else {
                logger.error("在以下位置都没有找到output字段:");
                logger.error("- rootNode.output: {}", rootNode.has("output"));
                logger.error("- dataNode: {}", dataNode);
                if (dataNode != null) {
                    logger.error("- dataNode.output: {}", dataNode.has("output"));
                    logger.error("- dataNode字段列表: {}", dataNode.fieldNames());
                }
                logger.error("- rootNode字段列表: {}", rootNode.fieldNames());
            }

            if (outputText == null || outputText.trim().isEmpty()) {
                logger.error("=== 解析失败：未找到output内容 ===");
                throw new RuntimeException("评估响应中未找到output内容");
            }

            logger.info("找到output内容: {}", outputText);

            // 从output中提取JSON部分
            String jsonPart = extractJsonFromOutput(outputText);
            logger.info("提取的JSON部分: {}", jsonPart);
            
            JsonNode evaluationNode = objectMapper.readTree(jsonPart);
            logger.info("解析后的评估节点: {}", evaluationNode);

            // 转换为Map
            Map<String, Object> result = objectMapper.convertValue(evaluationNode, Map.class);
            logger.info("=== 解析成功，返回结果 ===");
            return result;

        } catch (Exception e) {
            logger.error("=== 解析评估响应失败 ===", e);
            throw new RuntimeException("解析评估响应失败: " + e.getMessage(), e);
        }
    }

    /**
     * 从output文本中提取JSON部分
     */
    private String extractJsonFromOutput(String output) {
        // 查找JSON代码块
        int startIndex = output.indexOf("```json");
        int endIndex = output.indexOf("```", startIndex + 7);
        
        if (startIndex != -1 && endIndex != -1) {
            return output.substring(startIndex + 7, endIndex).trim();
        }

        // 如果没有代码块标记，尝试查找直接的JSON
        startIndex = output.indexOf("{");
        endIndex = output.lastIndexOf("}");
        
        if (startIndex != -1 && endIndex != -1 && endIndex > startIndex) {
            return output.substring(startIndex, endIndex + 1);
        }

        throw new RuntimeException("无法从响应中提取JSON内容");
    }

    /**
     * 将改进建议数组转换为前端期望的对象格式
     */
    private Map<String, Object> convertImprovementsArrayToMap(Object improvementsObj) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            if (improvementsObj instanceof List) {
                List<?> improvementsList = (List<?>) improvementsObj;
                
                // 将数组转换为分类格式，前端期望的格式
                List<String> technicalItems = new ArrayList<>();
                List<String> expressionItems = new ArrayList<>();
                
                for (Object item : improvementsList) {
                    String improvement = item.toString();
                    // 根据内容简单分类，可以根据实际需要调整分类逻辑
                    if (improvement.contains("技术") || improvement.contains("代码") || improvement.contains("算法") || 
                        improvement.contains("架构") || improvement.contains("性能") || improvement.contains("框架")) {
                        technicalItems.add(improvement);
                    } else {
                        expressionItems.add(improvement);
                    }
                }
                
                if (!technicalItems.isEmpty()) {
                    result.put("技术表达", technicalItems);
                }
                if (!expressionItems.isEmpty()) {
                    result.put("表达能力", expressionItems);
                }
                
                // 如果没有分类成功，使用默认分类
                if (result.isEmpty() && !improvementsList.isEmpty()) {
                    List<String> generalItems = new ArrayList<>();
                    for (Object item : improvementsList) {
                        generalItems.add(item.toString());
                    }
                    result.put("综合建议", generalItems);
                }
            }
        } catch (Exception e) {
            logger.warn("转换改进建议格式失败，使用默认格式", e);
            // 使用默认改进建议
            result.put("技术表达", Arrays.asList("建议补充更多技术细节", "增加代码示例说明"));
            result.put("表达能力", Arrays.asList("使用STAR法则结构化回答", "控制语速，保持逻辑清晰"));
        }
        
        return result;
    }

    /**
     * 保存评估结果到数据库
     */
    private void saveEvaluationResult(Long userId, String sessionId, Map<String, Object> evaluationResult) {
        try {
            // 解析评估结果
            Map<String, Object> sessionEvaluation = (Map<String, Object>) evaluationResult.get("session_evaluation");
            List<Map<String, Object>> answerEvaluations = (List<Map<String, Object>>) evaluationResult.get("answer_evaluations");

            // 更新面试会话的评估信息
            BigDecimal totalScore = new BigDecimal(sessionEvaluation.get("total_score").toString());
            BigDecimal positionMatchRate = new BigDecimal(sessionEvaluation.get("position_match_rate").toString());
            String comprehensiveRating = sessionEvaluation.get("comprehensive_rating").toString();

            interviewSessionMapper.completeSession(sessionId, LocalDateTime.now(), 
                totalScore, positionMatchRate, comprehensiveRating);

            // 保存详细分析到interview_analysis表
            InterviewAnalysis analysis = new InterviewAnalysis(userId, sessionId);
            analysis.setTechnicalScore(new BigDecimal("85.0")); // 技术得分（可以从评估结果中提取）
            analysis.setExpressionScore(new BigDecimal("78.0")); // 表达得分
            analysis.setLogicScore(new BigDecimal("82.0")); // 逻辑得分
            analysis.setExperienceScore(new BigDecimal("88.0")); // 经验得分
            
            // 保存优势和改进建议
            analysis.setStrengths(objectMapper.writeValueAsString(sessionEvaluation.get("key_strengths")));
            analysis.setWeaknesses(objectMapper.writeValueAsString(sessionEvaluation.get("key_improvements")));
            
            // 将key_improvements数组转换为前端期望的对象格式
            Map<String, Object> improvementsMap = convertImprovementsArrayToMap(sessionEvaluation.get("key_improvements"));
            analysis.setImprovements(objectMapper.writeValueAsString(improvementsMap));
            analysis.setNextSteps("根据评估结果，建议继续加强技术实践和表达能力");

            interviewAnalysisMapper.insertAnalysis(analysis);

            // 更新每个答案的评估信息
            if (answerEvaluations != null) {
                for (Map<String, Object> answerEval : answerEvaluations) {
                    Integer questionId = (Integer) answerEval.get("question_id");
                    Integer score = (Integer) answerEval.get("score");
                    Map<String, Object> analysisInfo = (Map<String, Object>) answerEval.get("analysis");
                    Map<String, Object> keywordMatch = (Map<String, Object>) answerEval.get("keyword_match");

                    // 查找对应的答案记录
                    List<InterviewAnswer> answers = interviewAnswerMapper.selectAnswersByUserAndSession(userId, sessionId);
                    for (InterviewAnswer answer : answers) {
                        if (answer.getQuestionId().equals(questionId)) {
                            answer.setAiScore(new BigDecimal(score));
                            answer.setAiAnalysis(analysisInfo.get("status").toString());
                            answer.setStrengthPoints(objectMapper.writeValueAsString(analysisInfo.get("highlights")));
                            answer.setImprovementPoints(objectMapper.writeValueAsString(analysisInfo.get("improvements")));
                            answer.setKeywordMatch(objectMapper.writeValueAsString(keywordMatch));
                            
                            interviewAnswerMapper.updateAnswer(answer);
                            break;
                        }
                    }
                }
            }

            logger.info("评估结果已保存: sessionId={}", sessionId);

        } catch (Exception e) {
            logger.error("保存评估结果失败: sessionId={}", sessionId, e);
            throw new RuntimeException("保存评估结果失败: " + e.getMessage(), e);
        }
    }

    /**
     * 获取面试分析结果
     */
    public Map<String, Object> getAnalysisResult(Long userId, String sessionId) {
        try {
            // 验证权限
            if (!interviewSessionMapper.userOwnsSession(userId, sessionId)) {
                throw new RuntimeException("无权访问此面试记录");
            }

            // 获取分析结果
            InterviewAnalysis analysis = interviewAnalysisMapper.findBySessionId(sessionId);
            if (analysis == null) {
                throw new RuntimeException("分析结果不存在，请先进行评估");
            }

            // 获取会话和答案信息
            InterviewSession session = interviewSessionMapper.findBySessionId(sessionId);
            List<InterviewAnswer> answers = interviewAnswerMapper.selectAllAnswersByUserAndSession(userId, sessionId);

            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("session", session);
            result.put("analysis", analysis);
            result.put("answers", answers);

            return result;

        } catch (Exception e) {
            logger.error("获取分析结果失败: sessionId={}", sessionId, e);
            throw new RuntimeException("获取分析结果失败: " + e.getMessage(), e);
        }
    }
}